import App from "../framework/App";
import ccclass = cc._decorator.ccclass;
import {shareUtil} from "../framework/wx/ShareUtil";
import CommonUtil from "../framework/utils/CommonUtil";
import {wxApi} from "./api/WxApi";
import Wx from "../framework/wx/Wx";
import {userProfile} from "./entity/UserProfile";
import FightWindow from "./windows/FightWindow";
import {WxEvent} from "../framework/wx/WxEvent";
import {globalConfig} from "./consts/GlobalConfig";
import {notifyConfigSave, syncConfigsFromNet} from "./entity/ConfigHelper";
import MenuWindow from "./windows/MenuWindow";
import {bannerAds} from "../framework/wx/AdsProvider";
import {logger} from "./third-scripts/game_sdk/Logger";
import {timer} from "./utils/TimeSpan";
import {DefaultShareProvider} from "./utils/DefaultShareProvider";
import LoadResData from "../framework/LoadResData";

@ccclass
class MyApp extends App {

    public beforeLoad() {
        // this.setCollidEnable(true, true);

        globalConfig.init();

        logger.setup();
        timer.setup();

        logger.sendEvent("进入游戏");

        Wx.loginWeChat().then(resp => {
            return wxApi.login(resp.code || "anymouse")
        }).then((user) => {
            if (user.code == 0) {
                const userInfo = user.data.userInfo || {};
                userProfile.setInfo(user.data.uid, userInfo.nickName, userInfo.avatarUrl, user.data.token);

                // 延时3秒后再发此消息.
                CommonUtil.delay(2).then(() => {
                    if (Wx.isWeChatEnv()) {
                        // 发送on_SHOW 消息. 初始进APP,界面还未完全启动, 因此需要延时发送on_show消息.
                        shareUtil.procLaunchOption(((shareTicket, scene, query, referrerInfo) => {
                            this.sendMessage(WxEvent.ON_SHOW, [{shareTicket, scene, query, referrerInfo}]);
                        }));
                    } else {
                        this.sendMessage(WxEvent.ON_SHOW, [{}]);
                    }
                    // 发送登录成功消息.
                    this.sendMessage(WxEvent.ON_LOGIN_SUCCESS);
                });
                logger.sendEvent("登录成功", {time: timer.timeSpan()});
            } else {
                logger.sendEvent("登录失败", {time: timer.timeSpan()});
            }
            syncConfigsFromNet();
        });
        this.setCollidEnable(true, false);
        shareUtil.setContentProvider(new DefaultShareProvider());
        shareUtil.initShareMenu();

        bannerAds.setAdUnitId(globalConfig.bannerAdsId);
        LoadResData.initLoadResData();
        this.context.startWindow(MenuWindow).then(() => {
            this.context.preload(FightWindow);
        });

        this.addLoginTime();
    }

    public listen(): string[] {
        return [
            WxEvent.ON_HIDE, WxEvent.ON_SHOW, WxEvent.ON_LOGIN_SUCCESS,
        ];
    }

    public handleMessage(msg: string, args: any[]): boolean {
        switch (msg) {
            case WxEvent.ON_SHOW: {
                cc.log("WxEvent.ON_SHOW", args[0]);
                shareUtil.notifyOnShow();
                break;
            }
            case WxEvent.ON_HIDE: {
                cc.log("WxEvent.ON_HIDE");
                notifyConfigSave();
                wxApi.notifyUploadUserData();
                break;
            }
            case WxEvent.ON_LOGIN_SUCCESS: {
                cc.log("onLoginSuccess:");
                shareUtil.procLaunchOption((shareTicket: string, scene: number, query: any, referrerInfo: any) => {
                    if (query.scene === "invite" && query.UserId) {
                        if (query.UserId == userProfile.userId) {
                            cc.log("自己通过链接进入");
                            return
                        }
                        cc.log("邀请成功!!");
                        wxApi.loginFromShare(query.UserId, "invite");
                    }
                    this.checkSrcChannel(query);
                });
                logger.sendEvent("登录成功");
                break;
            }
        }
        return false;
    }

    private addLoginTime() {
        this.schedule(() => {
            // 检测在线时长.
        }, 60);
    }

    private checkSrcChannel(query: any) {
        if (query.hasOwnProperty("q_src")) {
            cc.log("==========从MJ二维码导入玩家.");
            logger.sendEvent("渠道打开", {from: query["q_src"]})
        }
    }
}